<template>
  <ElSelect filterable clearable :="$attrs" @change="onChange">
    <ElOption v-for="item in options" :key="item[valueKey]" :label="item[labelKey]" :value="item[valueKey]" />
  </ElSelect>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElSelect, ElOption } from 'element-plus'
interface Option {
  value: string | number | boolean;
  label: string | number;
  disabled?: boolean
}
interface Props {
  api: (data?: any) => Promise<Option[]>;
  data: object;
  valueKey: string;
  labelKey: string;
  widthLabel?: string;
}
const props = withDefaults(defineProps<Props>(), {
  api: () => Promise.resolve([]),
  data: () =>({}),
  valueKey: 'value',
  labelKey: 'label',
  widthLabel: ''
})

const options = ref<Option[]>([])

const onChange = val => {
  if (props.widthLabel) {
    const op = options.value.find(i => i[props.valueKey] === val)
    props.data[props.widthLabel] = op && op[props.labelKey]
  }
}

onMounted(() => {
  props.api(props.data)
    .then(res => {
      options.value = res
    })
})
</script>
